package com.lsk.mps.backend.security;

import com.lsk.mps.backend.util.ResponseUtil;
import com.lsk.mps.backend.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import sun.security.util.Password;

import java.io.PrintWriter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginProcessingUrl("/api/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler((request, response, authentication) -> {
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write(ResponseUtil.buildSuccessResponse("Success"));
                })
                .failureHandler((request, response, exception) -> {
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write(ResponseUtil.buildFailedResponse(new StatusCode(403, exception.getMessage())));
                })
                .permitAll()
                .and()
                .exceptionHandling()
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write(ResponseUtil.buildFailedResponse(new StatusCode(403, "Forbidden")));
                })
                .authenticationEntryPoint((request, response, authException) -> {
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write(ResponseUtil.buildFailedResponse(new StatusCode(403, "Login needed")));
                })
                .and()
                .authorizeRequests()
                .antMatchers("/api/admin/*").hasRole("ADMIN")
                .antMatchers("/api/manager/*").hasAnyRole("ADMIN", "MANAGER")
                .antMatchers("/api/user/*").authenticated()
                .and()
                .csrf()
                .disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);
    }
}
